/*
 * @Author: your name
 * @Date: 2022-02-10 16:23:52
 * @LastEditTime: 2022-02-10 17:22:54
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \jike\src\pages\Login\index.js
 */
import { Component } from 'react';
import { Form, Input, Button, Checkbox, Card, message } from 'antd';

import logoSrc from 'assets/logo.png';
import styles from './index.module.scss';
import { loginAPI } from 'api/user';
import { setToken } from 'utils/storage';

export default class Login extends Component {
  handleSubmit = async (values) => {
    try {
      // 1. 发登录请求
      const res = await loginAPI(values);
      // 2. 存token，到localStore
      setToken(res.data.token);
      // 3. this.props.history跳转
      this.props.history.push('/');
      // 4.提示登录成功
      // 💥 message的持续事件是以秒为单位
      message.success('登录成功', 1);
    } catch (error) {
      // 5. 处理异常的情况
      message.error(error.response.data.message);
    }
  };
  render() {
    return (
      <div className={styles.login}>
        <Card className={styles.loginContainer}>
          <img src={logoSrc} alt="" className="login-logo" />
          <Form
            autoComplete="off"
            onFinish={this.handleSubmit}
            initialValues={{
              mobile: '13811111111',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                {
                  required: true,
                  message: '手机号码不能为空',
                },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入11位手机号码',
                },
              ]}
            >
              <Input placeholder="请输入手机号码" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: '验证码不能为空',
                },
                {
                  pattern: /^\d{6}$/,
                  message: '请输入6位验证码',
                },
              ]}
            >
              <Input placeholder="请输入6位验证码" />
            </Form.Item>

            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) => {
                    if (value) {
                      return Promise.resolve();
                    } else {
                      return Promise.reject('数据不对');
                    }
                  },
                },
              ]}
            >
              <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button block type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
